/*
 * Copyright 2016-2017 TVI Go Easy.
 * Created on 2017/10/26 17:34
 */
package com.gitee.mechanic.shiro.utils;

import org.apache.shiro.crypto.RandomNumberGenerator;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.util.Assert;
import org.apache.shiro.util.ByteSource;

/**
 * Shiro 密码工具类
 *
 * @author mechanic
 */
public class PasswordUtils {
    /**
     * 利用Shiro的盐值加密法对密码进行加密
     *
     * @param password       需要加密的密码
     * @param algorithm      加密方式
     * @param hashIterations 加密迭代次数
     * @return Password
     */
    public static Password encrypt(String password, String algorithm, int hashIterations) {
        Assert.notNull(password, "密码不能为空。");
        Assert.notNull(algorithm, "加密方式不能为空。");
        //随机生成盐值
        RandomNumberGenerator randomNumberGenerator = new SecureRandomNumberGenerator();
        String salt = randomNumberGenerator.nextBytes().toHex();
        //密码加密
        String encryptPassword = new SimpleHash(
          algorithm,
          password,
          ByteSource.Util.bytes(salt),
          hashIterations
        ).toHex();
        return new Password(salt, encryptPassword);
    }
}
